
import 'package:flutter/material.dart';
import 'package:flutter_boost/boost_navigator.dart';
import 'package:flutter_sizefit/flutter_sizefit.dart';
import 'package:flutter_xiecheng/core/extension_business/custom_print.dart';
import 'package:flutter_xiecheng/core/model/search_model.dart';
import 'package:flutter_xiecheng/core/viewmodel/search_request.dart';
import 'package:flutter_xiecheng/core/widget/webview.dart';
import 'package:flutter_xiecheng/gen_a/custom_asset.dart';
import 'package:flutter_xiecheng/page/search/search_bar.dart';

const TYPES = [
  'channelgroup',
  'gs',
  'plane',
  'train',
  'cruise',
  'district',
  'food',
  'hotel',
  'huodong',
  'shop',
  'sight',
  'ticket',
  'travelgroup',
];

class SearchPage extends StatefulWidget {
  /// 是否隐藏左边的返回按钮
  final bool hideLeft;
  /// 搜索的url
  final String searchUrl;
  /// 搜素关键字
  final String keyword;
  /// 默认文案
  final String hint;

  const SearchPage({Key key, this.hideLeft = true, this.searchUrl, this.keyword, this.hint = '搜索呀'}) : super(key: key);

  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  /// 搜索回来的model
  SearchModel searchModel;
  /// 搜搜的关键字
  String keyword;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    keyword = widget.keyword;
    /// 请求
    requestSearch();
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: Column(
        children: [
          appbar(),
          MediaQuery.removePadding(
              removeTop: true,
              context: context,
              child: Expanded(
                flex: 1,
                child: ListView.builder(
                    itemCount: searchModel?.data?.length ?? 0,
                    itemBuilder: (BuildContext context, int index){
                      return _item(context, index);
                    }),
              ))
        ],
      ),
    );
  }

  /// 文字发生变化
  _onTextChange(String content) {
    keyword = content;
    if(content.length == 0) {
      setState(() {
        searchModel = null;
      });
      return;
    }
    requestSearch();
  }

  /// 数据的请求
  requestSearch() {
    print('数据进行请求-------$keyword------------');
    JKSearchRequest.getSearch(keyword).then((value) {
      setState(() {
        print('🚀输入的内容：$keyword 返回的内容：${value.keyword}');
        if (keyword == value.keyword) {
          searchModel = value;
        }
      });
    }).catchError((e) {
      print("错误内容：$e");
    });
  }

  /// 单个的item
  Widget _item(BuildContext context, int index) {
    if(searchModel == null || searchModel.data == null) return null;
    SearchItem item = searchModel.data[index];
    print('火箭------${item.word}');
    return GestureDetector(
      onTap: () {
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          return JKWebView(url: item.url, title: '详情',);
        }));
      },
      child: Container(
        padding: EdgeInsets.all(10),
        decoration: BoxDecoration(
          border: Border(bottom: BorderSide(width: 0.3, color: Colors.grey))
        ),
        child: Row(
          children: [
            Container(
              margin: EdgeInsets.all(1),
              child: Image(
                height: 26,
                width: 26,
                image: AssetImage(_itemImage(item.type)),
              ),
            ),
            Column(
              children: [
                Container(width: 300, margin: EdgeInsets.only(top: 5), child: _title(item),),
                Container(width: 300, child: _subTitle(item),)
              ],
            )
          ],
        ),
      ),
    );
  }

  /// 加载图片
  _itemImage(String imageType) {
    if(imageType == null) return JKAssets.assets_images_type_travelgroup;
    String path = 'travelgroup';
    for (final val in TYPES) {
      if (imageType.contains(val)) {
        path = val;
        break;
      }
    }
    return 'assets/images/type_$path.png';
  }
  
  /// 标题
  _title(SearchItem item) {
    if (item == null)  return null;
    List<TextSpan> spans = [];
    spans.addAll(_keyWordsTextSpans(item.word, searchModel.keyword));
    spans.add(TextSpan(text: ' ' + (item.districtname ?? ""), style: TextStyle(fontSize: 16, color: Colors.grey)));
    return RichText(text: TextSpan(children: spans));
  }

  // 标题的富文本
  _keyWordsTextSpans(String word, String keyWord) {
    List<TextSpan> spans = [];
    if (word == null || word.length == 0) return spans;
    List<String> arr = word.split(keyWord);
    TextStyle normalStyle = TextStyle(fontSize: 16, color: Colors.black87);
    TextStyle keywordStyle = TextStyle(fontSize: 16, color: Colors.orange);
    for (int i = 0; i < arr.length; i++) {
      if ((i + 1) % 2 == 0) {
        print("富文本i = $i");
        spans.add(TextSpan(text: keyword, style: keywordStyle));
      }
      String val = arr[i];
      if (val != null && val.length > 0) {
        spans.add(TextSpan(text: val, style: normalStyle));
      }

      print("哈哈💣：${(i + 1) % 2} i = $i 值：$val 长度：${val.length}");
    }
    return spans;
  }
  
  /// 副标题
  _subTitle(SearchItem item) {
    return RichText(
        text: TextSpan(
          children: [
            TextSpan(text: "实时价格  ", style: TextStyle(fontSize: 16, color: Colors.orange)),
            TextSpan(text: "评价", style: TextStyle(fontSize: 12, color: Colors.grey))
          ]
        )
    );
  }

  /// 自定义导航栏
  Widget appbar() {
    return Column(
      children: [
        Container(
          decoration: BoxDecoration(
              gradient: LinearGradient(colors: [Color(0x66000000), Colors.transparent], begin: Alignment.topCenter, end: Alignment.bottomCenter)
          ),
          child: Container(
            height: JKSizeFit.navigationBarHeight,
            padding: EdgeInsets.fromLTRB(0, JKSizeFit.topStatusHeight, 0, 0),
            decoration: BoxDecoration(
                color: Colors.white
            ),
            child: SearchBar(
              hideLeft: widget.hideLeft,
              defaultText: widget.keyword,
              hintText: widget.hint,
              leftButtonClick: () {
                setState(() {
                  BoostNavigator.instance.pop();
                });
              },
              onChange: _onTextChange,
            ),
          ),
        ),
        Container(
          height: searchModel != null ? 0.5 : 0,
          decoration: BoxDecoration(
              boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 0.5)]
          ),
        )
      ],
    );
  }
}
